package com.sencorsta.ids.core.tcp.socket.server;

import com.sencorsta.ids.core.application.Application;
import com.sencorsta.ids.core.configure.TypeProtocol;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.opensocket.OpenMessage;
import com.sencorsta.ids.core.tcp.socket.protocol.RpcMessage;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * IO处理器，所有接收到的消息put到队列里，等待处理器分发处理
 * @author ICe
 */
public final class RpcChannelHandler extends ChannelInboundHandlerAdapter {

	//private RpcServerBootstrap server;

//	public RpcChannelHandler(RpcServerBootstrap server) {
//		this.server = server;
//	}
	
	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		//Out.debug("handlerAdded Session:", ctx.channel());
		Out.trace("RpcServer添加:",ctx.channel());
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		Out.info("RpcServer异常:",ctx.channel()," ",cause.getMessage());
		//cause.printStackTrace();
		ctx.close();
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		Channel channel = ctx.channel();
		//Out.info("handlerRemoved : ", channel);
		//GGame.getInstance().onServiceClose(channel);
		Out.trace("RpcServer移除:",ctx.channel());
		Application.getInstance().onServiceClose(channel);
		
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object packet) throws Exception {
		RpcMessage msg=(RpcMessage) packet;
		Out.trace(" ");
		Out.trace("RpcServer新消息:",ctx.channel()," ",msg);
		switch (msg.header.type) {
			case TypeProtocol.TYPE_RPC_REQ: {
				Application.getInstance().addReceiveToDispatcher(msg);
				break;
			}
			case TypeProtocol.TYPE_RPC_RES: {
				Application.getInstance().sendOpenMessage(msg);
				break;
			}
			case TypeProtocol.TYPE_RPC_PUSH: {
				Application.getInstance().sendOpenMessage(msg);
				break;
			}
			default:Out.warn("未知协议类型："+msg.header.type);
				break;
		}
		//server.addReceiveToApplication(msg);
	}
	
}
